package com.nineclock.approve.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.approve.dto.*;
import com.nineclock.approve.mapper.ApproveDefinitionMapper;
import com.nineclock.approve.pojo.ApproveDefinition;
import com.nineclock.approve.service.ActivitiService;
import com.nineclock.approve.service.ApproveDefinitionService;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.common.utils.JsonUtils;
import com.nineclock.common.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Service
@Slf4j
public class ApproveDefinitionServiceImpl implements ApproveDefinitionService {

    @Autowired
    ApproveDefinitionMapper approveDefinitionMapper;

    @Override
    public List<ApproveGroupDefinitionDto> queryApproveGroupDefinition() {

        LambdaQueryWrapper<ApproveDefinition> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApproveDefinition::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper.eq(ApproveDefinition::getIsValid, 1);
        //根据条件获取 列表数据
        List<ApproveDefinition> approveDefinitions = approveDefinitionMapper.selectList(wrapper);

        //把列表数据 根据 groupType字段分组
        Map<String, List<ApproveDefinition>> map = approveDefinitions.stream().collect(Collectors.groupingBy(ApproveDefinition::getGroupType));


        List<ApproveGroupDefinitionDto> approveGroupDefinitionDtoList = new ArrayList<>();

        //循环 map集合所有的key
        for (String groupType : map.keySet()) {
            ApproveGroupDefinitionDto approveGroupDefinitionDto = new ApproveGroupDefinitionDto();
            approveGroupDefinitionDto.setGroupType(groupType);
            //根据key(groupType) ，获取流程定义列表
            approveGroupDefinitionDto.setDefinitionList(map.get(groupType));

            approveGroupDefinitionDtoList.add(approveGroupDefinitionDto);
        }

        return approveGroupDefinitionDtoList;
    }

    @Autowired
    ActivitiService activitiService;

    /**
     * 如果有id ，是修改操作
     * 如果没有id ， 是新增操作
     * @param approveDefinitionSaveDto
     */
    @Override
    public void saveOrEdit(ApproveDefinitionSaveDto approveDefinitionSaveDto) {
        if( approveDefinitionSaveDto == null || approveDefinitionSaveDto.getBaseData() == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //获取 基础数据
        ApproveDefinitionBaseDataDto baseData = approveDefinitionSaveDto.getBaseData();
        //如果id为null，说明是新增操作
        if (baseData.getId() == null){
            //复制 基本信息到 流程定义对象
            ApproveDefinition definition = BeanHelper.copyProperties(baseData, ApproveDefinition.class);
            //设置 谁可以发起这个审批 字段
            List<AllowUserObjDto> allowUserList = baseData.getAllowUserJson();
            definition.setAllowUserJson(JsonUtils.toString(allowUserList));
            //表单数据
            List<ApproveDefinitionTableDataDto> tableData = approveDefinitionSaveDto.getTableData();
            definition.setFormJson(JsonUtils.toString(tableData));


            //设置 表单 的 列属性(扩展一个字段（filedKey）)
            List<ColumnObjDto> columnObjDtos = expandFieldKey(approveDefinitionSaveDto);
            definition.setColumns(JsonUtils.toString(columnObjDtos));

            //流程数据
            String flowData = approveDefinitionSaveDto.getFlowData();
            JSONArray jsonArray = JSONUtil.parseArray(flowData);
            //jsonArray 添加了一个字段 (nodeKey)
            expandParamWithNodeKey(jsonArray);
            definition.setFlowJson(JsonUtils.toString(jsonArray));


            //设置基础字段
            definition.setCompanyId(CurrentUserHolder.get().getCompanyId() +"");
            definition.setCreateTime(new Date());
            definition.setTableName("flow_"+UUIDUtils.getUUID()); //唯一的名称
            definition.setIsValid("1");

            approveDefinitionMapper.insert(definition);

            //把设计好的流程定义 部署到 activiti数据库中
            activitiService.deployBpmnToActiviti(definition);
        }
        //如果id不为null，则为修改操作
        else{
            //根据id从数据查询流程定义
            ApproveDefinition definition = approveDefinitionMapper.selectById(baseData.getId());
            //修改数据
            //设置 谁可以发起这个审批 字段
            List<AllowUserObjDto> allowUserList = baseData.getAllowUserJson();
            definition.setAllowUserJson(JsonUtils.toString(allowUserList));
            //表单数据
            List<ApproveDefinitionTableDataDto> tableData = approveDefinitionSaveDto.getTableData();
            definition.setFormJson(JsonUtils.toString(tableData));


            //设置 表单 的 列属性(扩展一个字段（filedKey）)
            List<ColumnObjDto> columnObjDtos = expandFieldKey(approveDefinitionSaveDto);
            definition.setColumns(JsonUtils.toString(columnObjDtos));

            //流程数据
            String flowData = approveDefinitionSaveDto.getFlowData();
            JSONArray jsonArray = JSONUtil.parseArray(flowData);
            //jsonArray 添加了一个字段 (nodeKey)
            expandParamWithNodeKey(jsonArray);
            definition.setFlowJson(JsonUtils.toString(jsonArray));

            //设置基础数据
            definition.setUpdateTime(new Date());
            definition.setGroupType(baseData.getGroupType());
            definition.setName(baseData.getName());
            definition.setDescription(baseData.getDescription());
            definition.setIcon(baseData.getIcon());
            definition.setOpinionPrompt(baseData.getOpinionPrompt());
            definition.setOpinionRequired(baseData.getOpinionRequired());
            definition.setSeq(baseData.getSeq());

            approveDefinitionMapper.updateById(definition);

            //删除原来的 activiti 流程
            activitiService.dropBpmnFromActiviti(definition);
            //把设计好的流程定义 部署到 activiti数据库中
            activitiService.deployBpmnToActiviti(definition);
        }

    }

    @Override
    public ApproveDefinitionResultDto queryById(String id) {
        if(id == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //根据id 查询流程定义
        ApproveDefinition definition = approveDefinitionMapper.selectById(id);

        //处理 基础部分
        ApproveDefinitionBaseDataDto baseData = BeanHelper.copyProperties(definition, ApproveDefinitionBaseDataDto.class);
        //设置 运行谁来发起这个申请
        String allowUserJson = definition.getAllowUserJson();
        baseData.setAllowUserJson(JsonUtils.toList(allowUserJson, AllowUserObjDto.class));

        //设置表单数据
        String formJson = definition.getFormJson();
        List<ApproveDefinitionTableDataResultDto> tableData = JsonUtils.toList(formJson, ApproveDefinitionTableDataResultDto.class);

        String flowJson = definition.getFlowJson();

        //创建 返回值
        ApproveDefinitionResultDto resultDto = new ApproveDefinitionResultDto();
        //设置三部分数据
        resultDto
                .setBaseData(baseData)
                .setTableData(tableData)
                .setFlowData(flowJson);

        return resultDto;
    }

    private void expandParamWithNodeKey(JSONArray jsonArray) {
        for(int i = 0; i < jsonArray.size(); i++){
            JSONObject jsonNode = (JSONObject) jsonArray.get(i);

            String nodeKey = jsonNode.getStr("nodeKey");
            if(StrUtil.isEmpty(nodeKey)){
                jsonNode.put("nodeKey", UUIDUtils.getUUID());
            }

            //处理网关节点的内部节点 nodeKey
            String type = jsonNode.getStr("type");
            if("condition".equals(type)){

                JSONArray batchArray = (JSONArray) jsonNode.get("node");
                if(batchArray!=null && batchArray.size()>0){

                    for (int j = 0; j < batchArray.size(); j++) {
                        JSONArray innerArray = (JSONArray) batchArray.get(j);

                        if(innerArray!=null && innerArray.size()>0){
                            for (int k = 0; k < innerArray.size(); k++) {
                                JSONObject node = (JSONObject) innerArray.get(k);
                                if(!node.containsKey("nodeKey")){
                                    node.put("nodeKey", UUIDUtils.getUUID());
                                }
                            }
                        }
                    }
                }
            }
        }
    }


    /**
     * 扩充参数 : fieldKey
     * @param approveDefinitionDto
     * @return
     */
    private List<ColumnObjDto> expandFieldKey(ApproveDefinitionSaveDto approveDefinitionDto) {
        List<ColumnObjDto> columns = new ArrayList<>();

        for (ApproveDefinitionTableDataDto tableData : approveDefinitionDto.getTableData()) {
            if(StrUtil.isEmpty(tableData.getFieldKey())){
                tableData.setFieldKey(UUIDUtils.getUUID());
            }

            columns.add(new ColumnObjDto(tableData.getFieldKey(), tableData.getLab(), tableData.getTitle(), "1"));
        }
        return columns;
    }
}
